package com.bawei.mdm2207alast.apps

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageInfo
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import coil.compose.AsyncImage
import com.bawei.mdm2207alast.R
import com.bawei.mdm2207alast.common.BaseTitle
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.launch

/**
 * 作者：赵亮
 * 时间：2024/12/16 15:33
 * 功能：本地应用
 */
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun LocalAppsPage(navController: NavController = rememberNavController()) {

    val context = LocalContext.current

    // 1. 数据
    val list = remember {
        SnapshotStateList<PackageInfo>()
    }

    LaunchedEffect(key1 = "") {
        launch {
            // 读取本地应用列表，添加到集合中
            val packageManager = context.packageManager
            val packageInfos = packageManager.getInstalledPackages(0)
            list.addAll(packageInfos)
        }
    }

    var packageInfo: PackageInfo? = null

    // 动态注册 卸载应用的广播
    context.registerReceiver(object : BroadcastReceiver() {
        override fun onReceive(p0: Context?, p1: Intent?) {
            // 从集合中移除数据
            list.remove(packageInfo)
        }
    }, IntentFilter(Intent.ACTION_PACKAGE_REMOVED).apply {
        addDataScheme("package")
    })

    Column {
        BaseTitle(navController = navController, title = "本地应用管理")

        // 展示
        LazyVerticalGrid(columns = GridCells.Fixed(3)) {
            items(list) {
                Column(modifier = Modifier.combinedClickable(
                    onClick = {
                        // ToastUtils.showShort("点击")
                        // 启动应用
                        AppUtils.launchApp(it.packageName)
                    },
                    onLongClick = {
                        // ToastUtils.showShort("长按")
                        // 卸载应用
                        AppUtils.uninstallApp(it.packageName)
                        packageInfo = it
                    }
                ), horizontalAlignment = Alignment.CenterHorizontally) {
                    AsyncImage(
                        placeholder = painterResource(id = R.drawable.icon64),
                        error = painterResource(id = R.drawable.icon1488),
                        modifier = Modifier.size(50.dp),
                        model = it.applicationInfo.loadIcon(context.packageManager),
                        contentDescription = null
                    )
                    Text(text = it.applicationInfo.loadLabel(context.packageManager).toString())
                }

            }
        }
    }
}

@Preview(showSystemUi = true)
@Composable
fun LocalAppsPagePreview() {
    LocalAppsPage()
}

